import dayjs from "dayjs"
import signMd5Utils from '@/utils/signMd5Utils'
const baseUrl = 'http://192.168.1.128:10999'
// const baseUrl='http://oyc.sidwit.com'

const gateway = {
  operate: '/operate',
  busscommon: '/busscommon',
  sysweixin: '/sysweixin',
  sysbase: '/sysbase',
  sysadopted: '/edc',
  sysklbase: '/edc',
  sysshop: '/edc',
  sysrural: '/sysrural',
  sysbuswork: '/edc',
  sysaiot: '/aiot'
}

const request = (url, method, data, showLoading,) => {
  return new Promise((resolve, reject) => {
    if (showLoading) {
      uni.showLoading({
        title: '加载中',
      })
    }
    let token = uni.getStorageSync('userInfo').sessionKey
    uni.request({
      url: baseUrl + url,
      method: method,
      data: data,
      header: {
        // 'app-id': uni?.getAccountInfoSync()?.miniProgram.appId || '',
        'Tenant-Id': '1753319714027192322',
        // 'third-session': token ? token : '',
        'X-Access-Token': token ? token :
          'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDc0MTg2NzgsInVzZXJuYW1lIjoiYWRtaW5veWMifQ.WD38O1vbi6mqi8S1bI3bvEmtrgllHy69Ci_lhBVK2Xw',
        'X-TIMESTAMP': dayjs().format('YYYYMMDDHHmmss'),
        'X-Sign': signMd5Utils.getSign(url, data)
      },
      success (res) {
        if (res.statusCode == 200) {
			// console.log(res.data);
          if (res.data.code == 200  || res.data.code==0) {
            resolve(res.data)
          }
		  if(res.data.message){
			  uni.showToast({
			    icon: 'none',
			    title: res.data.message
			  })
		  }
          // console.log(res.data);
          if (res.data.code == '60001' || res.data.code == '60002') {
            uni.showModal({
              title: '提示',
              content: res.data.message + '',
              success (res) {
                if (res.confirm) {
                  uni.clearStorageSync()
                  uni.reLaunch({
                    url: '/pages/home/index'
                  })
                }
              },
            })
            reject(res.data.message)
          }


        } else if (res.statusCode == 404) {
          uni.showModal({
            title: '提示',
            content: '接口请求出错，请检查手机网络',
            success (res) {

            }
          })
          reject()
        } else if (res.statusCode == 401) {
          uni.showModal({
            title: '提示',
            content: res.data.message,
            success (res) {
              if (res.confirm) {
                uni.clearStorageSync()
                uni.reLaunch({
                  url: '/pages/home/index'
                })
              }
            },
          })
          reject(res.data.message)

        } else {
          uni.showModal({
            title: '提示',
            content: res.data.message,
            success (res) {
            }
          })
          reject()
        }
      },
      fail (error) {
        uni.showModal({
          title: '提示',
          content: '接口请求出错：' + error.errMsg,
          success (res) { }
        })
        reject(error)
      },
      complete (res) {
        uni.hideLoading()
      }
    })
  })
}

const upload = (url, path) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl + url, // 服务器接口地址
      filePath: path,
      header: {
        'Tenant-Id': '1753319714027192322',
        // 'third-session': token ? token : '',
        'X-Access-Token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDc0MTg2NzgsInVzZXJuYW1lIjoiYWRtaW5veWMifQ.WD38O1vbi6mqi8S1bI3bvEmtrgllHy69Ci_lhBVK2Xw',

      },
      name: 'file', // 后台接收参数名称
      formData: {}, // 其他表单数据（非必需）

      success (res) {
        resolve(JSON.parse(res.data))
      },

      fail (err) { }
    })
  });
}
const getAction = (url, data, showLoading) => {
  return request(url, 'get', data, true)
}
const postAction = (url, data, showLoading) => {
  return request(url, 'post', data, true)
}
const deleteAction = (url, data, showLoading) => {
  return request(url, 'delete', data, true)
}
const uploadAction = (path) => {
  return upload('/sysbase/sys/common/uploadNew', path)
}


const fullImage = (url) => {
  if (url) {
    if (url.indexOf('http:') > -1 || url.indexOf('https:') > -1) {
      return url;
    } else if (url.indexOf('data:image') > -1) {
      return url;
    } else {
      return 'https://edu.xd.sidwit.com/' + url;
    }
  } else {
    return ''
  }
}

const wxLogin = function () {
  return new Promise((resolve, reject) => {
    if (uni.getStorageSync('userInfo')) {
      resolve()
      return
    }
    uni.showLoading({
      title: '登录中'
    })
    setTimeout(() => {
      uni.login({
        provider: 'weixin',
        success (res) {
          request('/sys/thirdLogin/oauth2/LoginNew', 'post', {
            jsCode: res.code
          }).then(rs => {
            uni.setStorageSync('userInfo', rs.data)
            resolve()
          })
        },
        fail (err) {
          reject()
        },
        complete () {
          uni.hideLoading()
        }
      })
    }, 1500)

  })

}






export const ajaxGetDictItems = (code, params) => getAction(`/sys/dict/getDictItems/${code}`, params);
export const loadCategoryData = (params) => getAction('/sys/category/loadAllData', params)
export {
  request,
  wxLogin,
  gateway,
  fullImage,
  getAction,
  postAction,
  deleteAction,
  uploadAction,
  baseUrl
}
